package com.dayuan.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dayuan.bean.Goods;
import com.dayuan.bean.ShopCart;
import com.dayuan.bean.ShopCartInfo;
import com.dayuan.dao.GoodsMapper;
import com.dayuan.dao.ShopCartMapper;
import com.dayuan.vo.ShopCartVo;

@Service
public class ShopCartService {

	@Resource
	private ShopCartMapper shopCartMapper;
	
	@Resource
	private GoodsMapper goodsMapper;

	/* 根据用户id查询购物车所有商品 */
	public List<ShopCartVo> selectShopCartByUserId(Integer userId) {
		
		List<ShopCartInfo> list = shopCartMapper.selectShopCartByUserId(userId);
		
		List<ShopCartVo> result = new ArrayList<>();
		for (ShopCartInfo shopCartInfo : list) {
			//用goods_id查询商品表
			Goods goods = goodsMapper.selectGoodsAllById(shopCartInfo.getGoods_id());
			//把vo放到list中返回前端
			ShopCartVo shopCartVo = new ShopCartVo();
			shopCartVo.setId(shopCartInfo.getId());
			shopCartVo.setNumber(shopCartInfo.getNumber());
			shopCartVo.setGoods_name(goods.getGood_name());
			shopCartVo.setPicture(goods.getPic_url());
			shopCartVo.setPrice(goods.getPrice());
			shopCartVo.setPromotion_price(goods.getPromotion_price());	
			result.add(shopCartVo);
		}
		
		return result;
	}

	/*根据购物车id删除商品*/
	public int deleteShopCart(Integer id) {
		return shopCartMapper.deleteShopCartInfo(id);
	}
	
	/*商品加入购物车*/
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void insertShopCart(Integer goodsId,Integer userId,Integer number) {
		try {
			ShopCart shopCart = shopCartMapper.selectShopCartById(userId);
			if(shopCart==null){
				 shopCart = new ShopCart();
				shopCart.setUser_id(userId);
				shopCartMapper.insertShopCart(shopCart);
			}
			//验证购物车详情表有没有这个商品
			ShopCartInfo shopCartInfo = new ShopCartInfo();
			shopCartInfo.setGoods_id(goodsId);
			shopCartInfo.setShopcart_id(shopCart.getId());
			ShopCartInfo sc = shopCartMapper.selectShopCartInfo(shopCartInfo);
			if(sc!=null){
				sc.setNumber(sc.getNumber()+number);
				sc.setId(sc.getId());
				shopCartMapper.updateShopCartInfo(sc);
			}else {
				ShopCartInfo shopCartInfo1 = new ShopCartInfo();
				shopCartInfo1.setGoods_id(goodsId);
				shopCartInfo1.setNumber(number);
				shopCartInfo1.setShopcart_id(shopCart.getId());
				shopCartMapper.insertShopCartInfo(shopCartInfo1);
			}
			
			
		} catch (Exception e) {
			throw e;
		}
		
		
	}

	/*修改物品数量*/
	public int updateShopCartInfo(Integer id,Integer number){	
		ShopCartInfo shopCartInfo = new ShopCartInfo();
		shopCartInfo.setId(id);
		shopCartInfo.setNumber(number);		
		return shopCartMapper.updateShopCartInfo(shopCartInfo);
	}
	
	
}
